// 该文件专门用于创建整个应用的路由器
import VueRouter from "vue-router";
// 引入组件
import AboutPage from "@/pages/AboutPage";
import HomePage from "@/pages/HomePage";
import MessagePage from "@/pages/MessagePage";
import NewsPage from "@/pages/NewsPage";
import DetailPage from "@/pages/DetailPage";
// 创建并暴露一个路由器
const router = new VueRouter({
  mode: "history",
  routes: [
    {
      name: "guanyu",
      path: "/about",
      component: AboutPage,
      meta: {
        title: "关于",
      },
    },
    {
      name: "zhuye",
      path: "/home",
      component: HomePage,
      meta: {
        title: "主页",
      },
      children: [
        {
          name: "xiaoxi",
          path: "message", // 不加斜杠！
          component: MessagePage,
          meta: {
            isAuth: true,
            title: "消息",
            beforeEnter: (to, from, next) => {
              console.log(to, from, next);
            },
          },
          children: [
            {
              name: "xiangqing",
              path: "detail",
              component: DetailPage,
              meta: {
                isAuth: true,
                title: "详情",
              },
              props($route) {
                return {
                  id: $route.query.id,
                  title: $route.query.title,
                };
              },
            },
          ],
        },
        {
          name: "xinwen",
          path: "news",
          component: NewsPage,
          meta: {
            isAuth: true,
            title: "新闻",
          },
        },
      ],
    },
  ],
});
// 全局前置路由守卫——初始化、每次路由切换之前被调用
router.beforeEach((to, from, next) => {
  console.log("前置路由:", to, from);
  if (to.meta.isAuth) {
    //是否需要权限判断设置
    if (localStorage.getItem("school") === "atguigu") {
      next();
    } else {
      alert("权限不够！");
    }
  } else {
    next();
  }
});

router.afterEach((to, from) => {
  console.log("后置路由", to, from);
  if (to.meta.title) {
    document.title = to.meta.title;
  } else {
    document.title = "test_vue";
  }
});

export default router;
